<template>
  <div class="rule-form">
    <n-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-placement="top"
      size="medium"
    >
      <!-- 基本信息 -->
      <n-form-item label="规则名称" path="name">
        <n-input
          v-model:value="formData.name"
          placeholder="请输入规则名称"
          clearable
        />
      </n-form-item>

      <n-form-item label="规则描述" path="description">
        <n-input
          v-model:value="formData.description"
          type="textarea"
          placeholder="请输入规则描述（可选）"
          :rows="2"
          clearable
        />
      </n-form-item>

      <n-form-item label="启用状态" path="enabled">
        <n-switch v-model:value="formData.enabled" />
      </n-form-item>

      <!-- 条件配置 -->
      <n-form-item label="触发条件">
        <div class="conditions-section">
          <div
            v-for="(condition, index) in formData.conditions"
            :key="index"
            class="condition-item"
          >
            <n-space>
              <n-select
                v-model:value="condition.field"
                placeholder="字段"
                style="width: 120px"
                :options="fieldOptions"
              />
              
              <n-select
                v-model:value="condition.operator"
                placeholder="操作符"
                style="width: 140px"
                :options="operatorOptions"
              />
              
              <n-input
                v-model:value="condition.value"
                placeholder="值"
                style="width: 200px"
                clearable
              />
              
              <n-button
                @click="removeCondition(index)"
                type="error"
                size="small"
                circle
              >
                <template #icon>
                  <n-icon :component="RemoveOutline" />
                </template>
              </n-button>
            </n-space>
          </div>
          
          <n-button
            @click="addCondition"
            dashed
            style="width: 100%; margin-top: 8px"
          >
            <template #icon>
              <n-icon :component="AddOutline" />
            </template>
            添加条件
          </n-button>
        </div>
      </n-form-item>

      <!-- 行为配置 -->
      <n-form-item label="触发行为">
        <div class="actions-section">
          <div
            v-for="(action, index) in formData.actions"
            :key="index"
            class="action-item"
          >
            <n-space vertical style="width: 100%">
              <n-space>
                <n-select
                  v-model:value="action.type"
                  placeholder="行为类型"
                  style="width: 200px"
                  :options="actionTypeOptions"
                />
                
                <n-button
                  @click="removeAction(index)"
                  type="error"
                  size="small"
                  circle
                >
                  <template #icon>
                    <n-icon :component="RemoveOutline" />
                  </template>
                </n-button>
              </n-space>
              
              <n-input
                v-if="action.type === 'script'"
                v-model:value="action.script"
                type="textarea"
                placeholder="请输入JavaScript脚本代码"
                :rows="6"
                show-count
              />
            </n-space>
          </div>
          
          <n-button
            @click="addAction"
            dashed
            style="width: 100%; margin-top: 8px"
          >
            <template #icon>
              <n-icon :component="AddOutline" />
            </template>
            添加行为
          </n-button>
        </div>
      </n-form-item>
    </n-form>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <n-space justify="end">
        <n-button @click="handleCancel">取消</n-button>
        <n-button type="primary" @click="handleSave" :loading="saving">
          保存
        </n-button>
      </n-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import AddOutline from '@vicons/ionicons5/Add';
import RemoveOutline from '@vicons/ionicons5/Remove';
import type { Rule, RuleCondition, RuleAction } from '../types';

// Props
interface Props {
  rule?: Rule | null;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  save: [rule: Partial<Rule>];
  cancel: [];
}>();

// 状态
const formRef = ref();
const saving = ref(false);

// 表单数据
const formData = reactive({
  name: '',
  description: '',
  enabled: true,
  conditions: [] as RuleCondition[],
  actions: [] as RuleAction[]
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ]
};

// 选项数据
const fieldOptions = [
  { label: 'URL', value: 'url' },
  { label: '请求方法', value: 'method' },
  { label: '状态码', value: 'statusCode' },
  { label: '请求头', value: 'headers' },
  { label: '响应头', value: 'responseHeaders' },
  { label: '请求体', value: 'body' },
  { label: '响应体', value: 'responseBody' }
];

const operatorOptions = [
  { label: '包含', value: 'contains' },
  { label: '等于', value: 'equals' },
  { label: '匹配正则', value: 'matches' },
  { label: '不包含', value: 'not_contains' },
  { label: '不等于', value: 'not_equals' },
  { label: '开始于', value: 'starts_with' },
  { label: '结束于', value: 'ends_with' }
];

const actionTypeOptions = [
  { label: 'JavaScript脚本', value: 'script' },
  { label: '日志记录', value: 'log' },
  { label: '阻止请求', value: 'block' },
  { label: '修改请求', value: 'modify_request' },
  { label: '修改响应', value: 'modify_response' }
];

// 方法
function addCondition() {
  formData.conditions.push({
    field: 'url',
    operator: 'contains',
    value: ''
  });
}

function removeCondition(index: number) {
  formData.conditions.splice(index, 1);
}

function addAction() {
  formData.actions.push({
    type: 'script',
    script: '// 在这里编写JavaScript代码\n// request 和 response 对象可以直接使用\nconsole.log("规则触发:", request.url);'
  });
}

function removeAction(index: number) {
  formData.actions.splice(index, 1);
}

async function handleSave() {
  try {
    await formRef.value?.validate();
    saving.value = true;
    
    const ruleData: Partial<Rule> = {
      name: formData.name,
      description: formData.description,
      enabled: formData.enabled,
      conditions: formData.conditions.filter(c => c.field && c.operator && c.value),
      actions: formData.actions.filter(a => a.type && (a.type !== 'script' || a.script))
    };
    
    emit('save', ruleData);
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    saving.value = false;
  }
}

function handleCancel() {
  emit('cancel');
}

// 初始化表单数据
function initFormData() {
  if (props.rule) {
    formData.name = props.rule.name;
    formData.description = props.rule.description || '';
    formData.enabled = props.rule.enabled;
    formData.conditions = [...props.rule.conditions];
    formData.actions = [...props.rule.actions];
  } else {
    formData.name = '';
    formData.description = '';
    formData.enabled = true;
    formData.conditions = [];
    formData.actions = [];
  }
}

// 监听props变化
watch(() => props.rule, initFormData, { immediate: true });
</script>

<style scoped lang="less">
.rule-form {
  .conditions-section,
  .actions-section {
    width: 100%;
    
    .condition-item,
    .action-item {
      padding: 12px;
      border: 1px solid #e0e0e0;
      border-radius: 6px;
      margin-bottom: 8px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  
  .form-actions {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #e0e0e0;
  }
}
</style> 